<?php
namespace Manage\Model;
use \Think\Db;
use Think\Model;

class B2cOrdersModel extends Model{



    /**
     * 订单列表
     * pay_status 支付状态
     *  0 => app::get('b2c')->_('未支付'),
    1 => app::get('b2c')->_('已支付'),
    2 => app::get('b2c')->_('已付款至到担保方'), over
    3 => app::get('b2c')->_('部分付款'),    over
    4 => app::get('b2c')->_('部分退款'),
    5 => app::get('b2c')->_('全额退款'),
     *
     * ship_status 发货状态
     * 0 => app::get('b2c')->_('未发货'),
    1 => app::get('b2c')->_('已发货'),
    2 => app::get('b2c')->_('部分发货'),
    3 => app::get('b2c')->_('部分退货'),
    4 => app::get('b2c')->_('已退货'),
     *
     * received_status 收货状态
     * 0 => app::get('b2c')->_('未收货'),
     * 1 => app::get('b2c')->_('已收货'),
     *
     * 订单状态 status
     *
     * 'active' => app::get('b2c')->_('活动订单'),
     * 'dead' => app::get('b2c')->_('已作废'),
     * 'finish' => app::get('b2c')->_('已完成'),
     *
     * is_delivery 是否需要发货
     * Y => app::get('b2c')->_('是否需要发货'),
     * N => app::get('b2c')->_('是否需要发货'),
     *
     * pre_delivery_time 预约自提时间
     *
     * pickedup_bn   自提单号
     *
     * mark_text  操作员订单备注
     *
     *
     * shipping_id  配送方式（table:dlytype）
     *
     *
     */
    public function orderList($p,$view){


        $sub = array(
            0=>array('o.pay_status'=>'1','o.ship_status'=>array('in',array('0','2')),'o.status'=>'active'),// 待发货
            1=>array('o.pay_status'=>'1','o.ship_status'=>'1','o.received_status'=>'0','o.status'=>'active'),// 已发货
            2=>array('o.pay_status'=>'1','o.ship_status'=>'1','o.received_status'=>'1','o.status'=>'active'), //已收货  部分发货，不能确认收货 提示货没发完，收货定时任务，判断 发货状态是 1
            3=>array('o.pay_status'=>'0','o.status'=>'active'),//待支付
            4=>array('o.status'=>'dead'),//已经作废【未支付订单超时】，定时返回库存
            5=>array('o.status'=>'finish',),//已完成
            //6=>array('o.pay_status'=>'1','o.is_zt'=>1,'o.status'=>'active','o.local_id'=>session('userInfo.local_id')),//门店自提  [完成按钮]  状态 finish 库存操作
            6=>array('1=1'),
        );




        if($_GET['select'] == 'createtime'){
            $b_time = strtotime($_GET['begin_time']);
            $end_time = strtotime($_GET['end_time']);
            $where[] = 'o.'.$_GET['select'] . " > ".$b_time .' and '. 'o.'.$_GET['select']. " < ".$end_time;
        }


        if(!empty($_GET['search_val'])  && $_GET['select'] != 'createtime'){

            if ($_GET['select'] =='local_name'){
                $Prefix = 'ls.';
            }else {
                $Prefix = 'o.';
            }
            $where[]=$Prefix.$_GET['select']." like '%".$_GET['search_val']."%'";
        }




        $where[] = $sub[$view];

        $orderList =  $this->alias('o')->field("o.*,m.nickname,ls.local_name")
            ->join("left join ".C('DB_PREFIX')."b2c_members m on o.member_id = m.member_id")
            ->join("left join ".C('DB_PREFIX')."webpos_local_store ls on ls.local_id = o.local_id")
            ->where($where)
            ->page($p.",15")->order('o.createtime desc')->select();

        $orderCount =  $this->alias('o')->field("o.*,m.nickname,ls.local_name")
            ->join("left join ".C('DB_PREFIX')."b2c_members m on o.member_id = m.member_id")
            ->join("left join ".C('DB_PREFIX')."webpos_local_store ls on ls.local_id = o.local_id")
            ->where($where)
            ->order('o.createtime desc')->select();

       // $count   = $this->alias('o')->where($where)->count();// 查询满足要求的总记录数

        $count = count($orderCount);

        $Page       = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数
        $show       = $Page->show();// 分页显示输出


        foreach ($orderList as $k=>$item){
            $orderList[$k]['time'] = date('Y-m-d H:i:s',$item['createtime']);
            $orderList[$k]['detailurl'] =  U("orders/orderDetail/",['id'=>$item['order_id']]);;
            $orderList[$k]['pay_status'] = $item['pay_status'] == 1 ? '已支付':'未支付';
            $orderList[$k]['ship_status'] = $item['ship_status'] == 1 ? '已发货':'未发货';
            if($item['ship_status']==2){
                $orderList[$k]['ship_status'] = "部分发货";
            }

            if(($item['sell_ago']=='1' || $item['refund_status']=='1'|| $item['refund_status']=='2'|| $item['sell_front']=='1')&& I('get.view',0,intval())>0){
                $orderList[$k]['sell_later'] = "退货退款";
            }
            $orderList[$k]['is_zt'] = $item['is_zt'] == 1 ? '<span style="color: #ff2e49">自提订单</span>':'普通订单';
            //订单备注最新信息
            if(!empty($item['mark_text'])){
                $mark =unserialize( $item['mark_text']);
                $markContent = end($mark);
                $orderList[$k]['mark'] =  $markContent['mark_text'];
            }

            if ( $item['refund_front_status'] == '1') {
                $orderList[$k]['isback'] = '客户申请售后';
            }else{
                $orderList[$k]['isback'] = '订单正常';
            }


            $orderList[$k]['action'] = $this->actionButton($item['order_id'],$view);

        }

        $payList['page'] = $show;
        $payList['list'] = $orderList;


        if(!empty($payList)){
            return $payList;
        }else{
            return array('msg'=>'暂无订单','status'=>2);
        }


    }

    /**
     * @param string $order_id
     * 订单详细
     */

    public function orderDetail($order_id =''){

        $orderGoods['product'] =  M('b2c_order_items i')
            ->join("left join ".C('DB_PREFIX')."b2c_orders o on o.order_id = i.order_id")
            ->join("left join ".C('DB_PREFIX')."b2c_store_product sp on sp.product_id = i.product_id and sp.local_id = o.local_id")
            ->join("left join ".C('DB_PREFIX')."b2c_products p on p.product_id = sp.product_id")
            ->where(['i.order_id'=>$order_id])
            ->field("o.*,i.*,p.barcode,sp.freez,sp.store,p.unit")
            ->select();

        if(empty($orderGoods['product'])){
            return array("msg"=>"参数错误","status"=>0);
        }


        foreach ($orderGoods['product'] as $k=>$item){
            $orderGoods['detail']['shipping'] = $item['shipping']; //配送方式
            $orderGoods['detail']['ship_area'] = $item['ship_area'];//收货地区
            $orderGoods['detail']['ship_addr'] = $item['ship_addr'];//收货地址
            $orderGoods['detail']['ship_time'] = $item['ship_time'];//配送时间
            $orderGoods['detail']['ship_mobile'] = $item['ship_mobile'];//收货手机
            $orderGoods['detail']['ship_name'] = $item['ship_name'];//收货人姓名
            $orderGoods['detail']['payment'] = $item['payment'];//支付方式
            $orderGoods['detail']['weight'] = $item['weight'];//订单总重量
            $orderGoods['detail']['memo'] = $item['memo'];//客户附言
            $orderGoods['detail']['cost_freight'] = $item['cost_freight'];//配送费用
            $orderGoods['detail']['payed'] = $item['payed'];//订单支付金额
            $orderGoods['detail']['bonus_pay'] = $item['bonus_pay'];//使用奖金
            $orderGoods['detail']['total_amount'] = $item['total_amount'];//订单总额
            $orderGoods['detail']['cost_item'] = $item['cost_item'];//商品总额
            $orderGoods['detail']['pmt_order'] = $item['pmt_order'];//优惠抵扣金额
            $orderGoods['detail']['order_id'] = $item['order_id'];//订单ID
            $orderGoods['detail']['ship_status'] = $item['ship_status'];//发货状态
            $orderGoods['detail']['createtime'] = date('Y-m-d H:i:s',$item['createtime']) ;//下单时间
            $orderGoods['detail']['shipping_id'] = $item['shipping_id'];//配送方式ID
            $orderGoods['detail']['ship_zip'] = $item['ship_zip'];//收货人邮编
            $orderGoods['printing']['local_name'] =  $item['local_name'];//门店名称
            $orderGoods['printing']['shipping'] =  $item['shipping'];//配送方式
            $orderGoods['detail']['order_id'] =  $item['order_id'];//订单ID
            $orderGoods['detail']['member_id'] =  $item['member_id'];//订单ID
            $orderGoods['detail']['youhui'] = $item['cost_item'] - $item['total_amount'];//优惠金额
            if($item['pay_status'] == '1'){
                $orderGoods['detail']['is_zhifu'] = '已支付';//支付状态
            }else{
                $orderGoods['detail']['is_zhifu'] = '未支付';//支付状态
            }
            if(!empty($item['ship_area'])){
               $add = str_replace("mainland:","",$item['ship_area']);
               $pos =  strpos($add,':');
                if(!empty($pos)){
                    $orderGoods['detail']['ship_area'] = substr($add,0,$pos);
                }
            }
            $specVal = '';
            if(!empty($item['addon'])){
                $spec = unserialize($item['addon']);
                if(empty($spec['product_attr'])){
                    $specVal = "(".$item['addon'].")";
                }else{
                    $specVal .= "(";
                    foreach ($spec['product_attr'] as $k1=>$val){
                        $specVal .= $val['label'].":".$val['value'];
                    }
                    $specVal .= ")";

                }
                $sc ='';
                if(!empty($specVal)){
                    $sc = str_replace("(","",$specVal);
                    $sc = str_replace(")","",$sc);
                }
                $orderGoods['product'][$k]['spec_info'] = $sc;
                $orderGoods['product'][$k]['name'] = $item['name'].$specVal;
                $orderGoods['product'][$k]['needsend'] = $item['nums']-$item['sendnum'];

            }else{
                $orderGoods['product'][$k]['name'] = $item['name'];
                $orderGoods['product'][$k]['needsend'] = $item['nums']-$item['sendnum'];
            }


        }

        return $orderGoods;

    }


    /**
     * @param string $order
     * @param $view
     * @return mixed
     *
     */
    public function  actionButton($order='',$view){

        $url = U("orders/orderDetail/",['id'=>$order,'view' => $view]);
        $urlMark = U("orders/orderMark/",['id'=>$order]);
        $urlDeli = U("orders/orderDelivery/",['id'=>$order]);
        $finishBut = "isSure($order)";
        $ztBut = "isZtSure($order)";


            $butt = "<div class='edit-list'><ul class='order-edit'>	                
	                <li class='cur'><a href='".$url."'>查看订单</a></li>
	                <li><a href='".$urlMark."'>订单备注</a></li>
                </ul>
                </div>";

        $action  = array(
            /*0=>"<a href='#' >发货</a><a href='".$url."'>查看订单</a><a href='#'>订单备注</a>",*/
            0=>$butt,
            1=>"<div class='edit-list'><ul class='order-edit'>
                      <li><a href='".$url."' >查看订单</a></li>                                        
                        <li><a href='".$urlMark."'>订单备注</a></li>
                      </ul>
                </div>
            ",
              /*<li class='cur'><a href='javascript:void(0);' onclick='".$finishBut."'>完成</a></li>*/
            2=>"<div class='edit-list'><ul class='order-edit'>
                      <li><a href='".$url."' >查看订单</a></li>                                              
                         <li><a href='".$urlMark."'>订单备注</a></li>
                      </ul>
                </div>",
            3=>"<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='".$url."' >查看订单</a></li>
                      <li><a href='".$urlMark."'>订单备注</a></li>
                      </ul>
                </div>",
            4=>"<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='".$url."' >查看订单</a></li>
                    </ul>
                </div>",
            5=>"<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='".$url."' >查看订单</a></li>
                       <li><a href='" . $urlMark . "'>订单备注</a></li>
                      </ul>
                </div>",
         /*   6=>"<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='".$url."' >查看订单</a></li>
                       <li class='cur'><a href='javascript:void(0);' onclick='".$ztBut."'>完成</a></li>

                      </ul>
                </div>",*/
            6=>"<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='".$url."' >查看订单</a></li></ul></div>",
        );

        return $action[$view];

    }



    /**
     * 备注内容list
     */
    public function markList($order_id=''){

        $mark = $this->where(['order_id'=>$order_id])->field('mark_text')->find();

        if(!empty($mark)){
            $markArr = unserialize($mark['mark_text']);
            foreach ($markArr as $k=>$item){
                $markArr[$k]['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
            }

        }

        return $markArr;
    }

    /**
     * 订单日志
     */
    public function ordreLog($order_id = '')
    {

        $Log = M('b2c_order_log olog')
            ->join("left join " . C('DB_PREFIX') . "b2c_orders o on o.order_id = olog.rel_id")
            ->where(['olog.rel_id' => $order_id])->select();

        if (empty($Log)) {
            return array('msg' => '参数错误', 'status' => 0);
        }
        foreach ($Log as $k => $item) {
            $Log[$k]['time'] = date('Y-m-d H:i:s', $item['alttime']);

            if ($item['result'] == 'SUCCESS') {
                $Log[$k]['result'] = '成功';
            } else {
                $Log[$k]['result'] = '失败';
            }

            switch ($item['behavior']) {
                case 'creates':
                    $Log[$k]['behavior'] = "创建";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $item['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }


                    break;
                case 'updates':
                    $Log[$k]['behavior'] = "修改";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }
                    break;
                case 'payments':
                    $Log[$k]['behavior'] = "支付";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            // $Log[$k]['log_text'] .= $arr_log['txt_key'],$arr_log['data'][0],$arr_log['data'][1],$arr_log['data'][2];
                        }
                    }
                    break;
                case 'refunds':
                    $Log[$k]['behavior'] = "售后";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }
                    break;
                case 'delivery':
                    $Log[$k]['behavior'] = "发货";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            //  $Log[$k]['log_text'] .= $arr_log['txt_key'],$arr_log['data'][0],$arr_log['data'][1],$arr_log['data'][2],$arr_log['data'][3],$arr_log_text['data'][4],$arr_log['data'][5];
                        }
                    }
                    break;
                case 'member_refund':
                    $Log[$k]['behavior'] = "用户申请退款";
                    break;
                case 'member_refund_goods':
                    $Log[$k]['behavior'] = "用户申请退货退款";
                    break;

                case 'refund_fail':
                    $Log[$k]['behavior'] = "用户申请退货退款初审失败";
                    break;
                case 'received_status':
                    $Log[$k]['behavior'] = "后台自提确认收货";
                    break;
                case 'delete':
                    $Log[$k]['behavior'] = "用户删除订单";
                    break;
                case 'receive':
                    $Log[$k]['behavior'] = "用户确认收货";
                    break;
                case 'reship':
                    $Log[$k]['behavior'] = "退货";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            // $Log[$k]['log_text'] .= $arr_log['txt_key'],$arr_log['data'][0],$arr_log['data'][1],$arr_log['data'][2],$arr_log['data'][3],$arr_log_text['data'][4],$arr_log['data'][5];
                        }
                    }
                    break;
                case 'finish':
                    $Log[$k]['behavior'] = "完成";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }
                    break;
                case 'cancel':
                    $Log[$k]['behavior'] = "取消";
                    break;
                default:
                    break;
            }
        }

        return $Log;

    }





}